package search

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
	"titargo/matcher"
	"titargo/resource"
)

var imgMap = make(map[string]string)
var urlMap = make(map[string](map[string]string))

func getImgChan(imgChan chan *resource.Img) {
	for {
		img, ok := <-imgChan
		if !ok {
			break
		}
		src := img.Src
		imgMap[src] = src
	}
}

func getUrlChan(urlChan chan *resource.Link) {
	for {
		link, ok := <-urlChan
		if !ok {
			break
		}
		href := link.Href
		content := link.Content
		urlMap[href] = map[string]string{"href": href, "content": content}
	}
}

func spy(link *resource.Link, seed int, imgChan chan *resource.Img, urlChan chan *resource.Link) (interface{}, error) {
	fmt.Println(seed)
	defer func() {
		if r := recover(); r != nil {
			log.Println("[E]", r)
		}
	}()
	urlChan <- link
	url := link.Href
	req, _ := http.NewRequest("GET", url, nil)
	client := http.DefaultClient
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	body := resp.Body
	defer body.Close()

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("HTTP Response Error %d\n", resp.StatusCode)
	}

	bodyByte, _ := ioutil.ReadAll(body)
	resStr := string(bodyByte)
	var w sync.WaitGroup
	w.Add(2)

	go func() {
		imgmatcher := matcher.NewImgMatcher()
		imgmatcher.SetString(resStr, imgChan)
		w.Done()
	}()
	go func() {
		atagmatcher := matcher.NewAtagMatcher()
		atagmatcher.SetString(resStr)
		if seed > 0 {
			atagattrs := atagmatcher.GetAttr()
			newseed := seed - 1
			for _, attr := range atagattrs {
				_, isset := urlMap[attr.Href]
				if !isset {
					spy(attr, newseed, imgChan, urlChan)
				}
			}
		}
		w.Done()
	}()
	w.Wait()

	return resStr, err
}
